//
//  FirstViewController.m
//  HelloWord
//
//  Created by David Zou on 09-1-2.
//  Copyright 2009 China Post. All rights reserved.
//

#import "FirstViewController.h"
#import "DetailViewController.h"
#import "HelloWordAppDelegate.h"
#import "ProVocPage.h"


#define pvocPath @"/Users/david/Desktop/Applications/GRE.pvoc/"
#define kSumWords 1 

@implementation FirstViewController

@synthesize tableTitles;
@synthesize count;
@synthesize provocdata;
@synthesize pages;

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */


- (IBAction) settingAction:(id)sender
{
	NSLog(@"settingAction!");
}



 - (void)viewDidLoad {
	 [super viewDidLoad];
	 
	 NSString *fileName = [[NSBundle mainBundle] pathForResource:@"GRE_Data" ofType:nil]; 
	 NSString *docname = [NSHomeDirectory() stringByAppendingString:@"/Documents/GRE_Data"];
	 NSError *error;
	 [[NSFileManager defaultManager] copyItemAtPath:fileName toPath:docname error:&error];
	 NSLog(@"Error reading url at %@", [error localizedDescription]);
	 NSData *myData = [[[NSData alloc] initWithContentsOfFile:docname] autorelease];
	 
	 
	 self.title = @"Lessons";
	 self.tableTitles = [[NSMutableArray alloc] init];	 
	 self.count = [[NSMutableArray alloc] init];

	 if(!myData)
		 return nil;
	 self.provocdata = [NSKeyedUnarchiver unarchiveObjectWithData:myData];
	 
	 self.pages = [[self.provocdata allPages] retain];
	 NSEnumerator *enumerator = [self.pages objectEnumerator];

	 ProVocPage *page;
	 while (page = [enumerator nextObject]) {
		 [self.tableTitles addObject:[[NSString stringWithFormat: [page title]] retain]];

		 [self.count addObject:[[NSNumber numberWithInteger:[[page words] count]]retain]];
	 }

	
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 

- (bool)writeApplicationData:(NSData *)data forfileName:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	if (!documentsDirectory) {
		NSLog(@"Documents directory not found!");
		return NO;
	}
	NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
	return ([data writeToFile:appFile atomically:YES]);
}

- (NSData *)applicationDataFromFile:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
	NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
	return myData;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.tableTitles count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
	}
	cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:11];
	switch (indexPath.section) {
		case 0: 

			cell.textLabel.text = [self.tableTitles objectAtIndex:[indexPath row]];
			NSString *deteailText = [[NSString alloc] initWithFormat:@"%@ words",
									 [[self.count objectAtIndex:[indexPath row]] stringValue]];
			cell.detailTextLabel.text = deteailText;
			break;
	}
	return cell;
	
/*
    if (cell == nil) {
		CGRect cellFrame = CGRectMake(0, 0, 300, 65);
		cell = [[[UITableViewCell alloc] initWithFrame:cellFrame
			reuseIdentifier: CellIdentifier] autorelease];
		CGRect lessonsRect = CGRectMake(10, 5, 300, 35);
		UILabel *lessonsLabel = [[UILabel alloc] initWithFrame:lessonsRect];
		lessonsLabel.text = [self.tableTitles objectAtIndex:[indexPath row]];
		lessonsLabel.textAlignment = UITextAlignmentLeft;
		lessonsLabel.font = [UIFont boldSystemFontOfSize:20];
		[cell.contentView addSubview:lessonsLabel];
		[lessonsLabel release];

		CGRect sumWordsValueRect = CGRectMake(211, 26, 100, 15);
		UILabel *sumWordsValueLabel = [[UILabel alloc] initWithFrame:sumWordsValueRect];
		sumWordsValueLabel.text = @"words";
		sumWordsValueLabel.textAlignment = UITextAlignmentRight;
		sumWordsValueLabel.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:[UIFont smallSystemFontSize]];

		[cell.contentView addSubview:sumWordsValueLabel];
		[sumWordsValueLabel release];
		
		CGRect sumWordsRect = CGRectMake(200, 26, 70, 15);
		UILabel *sumWords = [[UILabel alloc] initWithFrame:sumWordsRect];
		sumWords.tag = kSumWords;
		sumWords.textAlignment = UITextAlignmentRight;
		sumWords.font = [UIFont boldSystemFontOfSize:13];
		[cell.contentView addSubview:sumWords];
		[sumWords release];
//        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	UILabel *sumWords = (UILabel *)[cell.contentView viewWithTag:kSumWords];
	sumWords.text = [[self.count objectAtIndex:[indexPath row]] stringValue];
*/
    return cell;
}

// called when the accessory view (disclosure button) is touched
- (void)onClick:(id)sender
{

	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	// Navigation logic may go here. Create and push another view controller.
	NSLog(@"Click the row!");
	DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
	ProVocPage *page = [self.pages objectAtIndex:[indexPath row]];
	dvController.cellText = (NSMutableArray *)[page words];

	dvController.title = [self.tableTitles objectAtIndex:[indexPath row]];
	[[self navigationController] pushViewController:dvController  animated:YES];
	[dvController release];	
}


- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
/*
- (NSInteger)tableView:(UITableView *)tableView 
	indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row = [indexPath row];
	return row;
}
*/
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 if (self = [super initWithStyle:style]) {
 }
 return self;
 }
 */
/*
 - (void)loadView {
 [super viewDidLoad];
 tableTitles = [[NSMutableArray alloc] init];
 for(int i=1; i<4; i++)
 [tableTitles addObject:[[NSString stringWithFormat:@"table cell #%d" , i]retain]];	
 }
 */




/*
 // Respond to a user tap
 - (void)tableView:(UITableView *)tableView selectionDidChangeToIndexPath:(NSIndexPath *)newIndexPath fromIndexPath:(NSIndexPath *)oldIndexPath 
 {
 printf("User selected row %d\n", [newIndexPath row] + 1);
 [self performSelector:@selector(deselect) withObject:nil afterDelay:0.5f];
 }
*/




/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 [self.tableView reloadData];
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */



- (void)dealloc {
	[pages release];
	[tableTitles release];
	[provocdata release];
    [super dealloc];
}


@end
